// 设置cookie

/**
 *
 * @param {*} exdays  保存天数
 * 使用
 *   文件目录
 *     总目录
 *       - src
 *         - utils
 *          - cookie.js
 *   单文件引入使用
 *   import { setCookie, getCookie, clearCookie, clearCookies } from '@/utils/cookie'
 *
 * setCookie(参数名(),参数值, 保存天数)  存储cookie
 * getCookie(参数名)                    获取cookie
 * clearCookie(参数名)                  清除cookie
 * clearCookies()                       清除所有cookie
 *
 */

// 存储cookie
function setCookie(cName = "", cValue = "", exdays = "") {
  var exdate = new Date(); // 获取时间
  exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); // 保存的天数
  if (!exdays) {
    window.document.cookie = cName + "=" + escape(JSON.stringify(cValue));
  } else {
    // 字符串拼接cookie
    window.document.cookie =
      cName +
      "=" +
      escape(JSON.stringify(cValue)) +
      ";path=/;expires=" +
      exdate.toGMTString();
  }
}

// 读取cookie
function getCookie(name) {
  if (document.cookie.length > 0) {
    var allcookies = document.cookie;
    name += "=";
    var pos = allcookies.indexOf(name);
    if (pos != -1) {
      var start = pos + name.length;
      var end = allcookies.indexOf(";", start);
      //这里是根据;分隔符来分隔出该名称的值，如果在设置Cookie时用的是,分隔，请替换成相应符号。
      if (end == -1) {
        end = allcookies.length;
      }
      var value = allcookies.substring(start, end);
      return JSON.parse(unescape(value));
    } else {
      return;
    }
  }
}

// 清除cookie
function clearCookie(name) {
  setCookie(name, "", -1); // 修改2值都为空，天数为负1天就好了
}

// 清除所有cookie
function clearCookies() {
  var temp = document.cookie.split(";");
  var name;
  for (var i = 0; ; i++) {
    if (!temp[i]) break;
    name = temp[i].split("=")[0];
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    document.cookie = name + "= ''" + "; expires=" + exp.toGMTString();
  }
}
export { setCookie, getCookie, clearCookie, clearCookies };
